package com.bbcare.followup.plat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.followup.plat.entity.PatientContentData;
import com.bbcare.followup.plat.service.IBaseChildService;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;

/**
 * @auther wuyz
 * @date 2018329
 * @version v.1
 * 基础儿保转归类型入表
 * 
 **/
@Service
public class BaseChildService implements IBaseChildService {
	
	@Autowired
	private IPatientQueueSchemeDAO patientQueueScheme;
	@Autowired
	private IPatientTaskContentDAO patientTaskConDao;
	@Autowired
	private IPatientDAO patientDao;
	 
	@Override
	public Map<String, Object> changeStatus(Map<String, Object> paramMap) throws Exception {
		//队列实例id
		String ptSchemeId = (String) paramMap.get("ptSchemeId");
		//更新时间
		String updateTime = (String) paramMap.get("updateTime");
		//任务id拼接
		String taskId = ptSchemeId+"changeStatus";
		//更新流水
		String updateAccept = (String) paramMap.get("updateAccept");
		String updateAuthor = (String) paramMap.get("updateAuthor");
		//用户id
		String userId = (String) paramMap.get("userId");
		//队列id
		String queueId = (String) paramMap.get("queueId");
		//租户id
		String tenantId = (String) paramMap.get("tenantId");
		//转归类型
		String changeStatus = (String) paramMap.get("changeStatus");
		//来源
		String sourceType = (String)paramMap.get("sourceType");
		//问题答案
		Map<String, Object> quesMap = (JSONObject) paramMap.get("contentData");
		

		Map<String,Object> map = new HashMap<String,Object>();
		map.put("changeStatus", changeStatus);
		map.put("updateTime", updateTime);
		map.put("updateAccept", updateAccept);
		map.put("updateAuthor", updateAuthor);
		map.put("id", ptSchemeId);
		map.put("ptSchemeId", ptSchemeId);
		map.put("userId", userId);
		map.put("queueId", queueId);
		map.put("tenantId", tenantId);
		map.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
		
		//查询患者是否存在
		List<Map<String,Object>> listPatient = patientDao.listPtArchInfoByCondition(map);
		if(CollectionUtils.isEmpty(listPatient)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"患者不存在，或者为非正常状态！"));
		}
		map.remove("userStatus");
		//更新队列实例表
		patientQueueScheme.updatePtQueueSchemeRecord(map);
		map.put("updateType", Constants.UPDATE_TYPE_INSERT);
		patientQueueScheme.insertPatientQueueSchemeHis(map);
		
		int upcdFlag = 0;
		//查看答案表中是否有数据，没有插入，没有更新
		map.put("taskId", taskId);
		 List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(map);
	        if (null != ptTaskConList && 0 != ptTaskConList.size()) {
	            // 非第一次录入，更新
	            upcdFlag = 0;
	        } else {
	            // 第一次录入，插入
	            upcdFlag = 1;
	        }
	        // 拼装问题和答案，准备入表pt_contentdata_info
	        if (MapUtils.isNotEmpty(quesMap)) {
	            if (1 == upcdFlag) {
	                List<PatientContentData> ptcInList = new ArrayList<PatientContentData>();
	                Iterator<String> iter = quesMap.keySet().iterator();
	                while (iter.hasNext()) {
	                    PatientContentData pcdVo = new PatientContentData();
	                    String queskey = iter.next();
	                    String quesvalue = (String) quesMap.get(queskey);
	                    pcdVo.setContentId("");
	                    pcdVo.setCreateTime(updateTime);
	                    pcdVo.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
	                    pcdVo.setQuestionAnswer(quesvalue);
	                    pcdVo.setQuestionId(queskey);
	                    pcdVo.setTaskId(taskId);
	                    pcdVo.setUpdateAccept(updateAccept);
	                    pcdVo.setUpdateTime(updateTime);
	                    pcdVo.setUpdateType(Constants.UPDATE_TYPE_INSERT);
	                    pcdVo.setUserId(userId);
	                    pcdVo.setPtSchemeid(ptSchemeId);
	                    pcdVo.setQueueId(queueId);
	                    pcdVo.setTenantId(tenantId);
	                    pcdVo.setTemplType("0");
	                    pcdVo.setSourceTypeCreate(sourceType);
	                    pcdVo.setSourceTypeUpdate(sourceType);
	                    ptcInList.add(pcdVo);
	                }
	                // 批量插入
	                patientTaskConDao.savePatientTaskContentDataBatch(ptcInList);
	                patientTaskConDao.savePatientTaskContentDataHisBatch(ptcInList);
	            } else {
	                // 逐条更新
	                List<PatientContentData> ptcInList = new ArrayList<PatientContentData>();
	                Iterator<String> iter = quesMap.keySet().iterator();
	                Map<String, Object> ptUpMapIn = new HashMap<String, Object>();
	                int pr = 0;
	                while (iter.hasNext()) {
	                    ptUpMapIn.clear();
	                    String queskey = iter.next();
	                    String quesvalue = (String) quesMap.get(queskey);
	                    ptUpMapIn.put("questionAnswer", quesvalue);
	                    ptUpMapIn.put("questionId", queskey);
	                    ptUpMapIn.put("taskId", taskId);
	                    ptUpMapIn.put("updateAccept", updateAccept);
	                    ptUpMapIn.put("updateTime", updateTime);
	                    ptUpMapIn.put("templType", "0");
	                    ptUpMapIn.put("sourceTypeUpdate", sourceType);
	                    pr = patientTaskConDao.updatePtContentDataInfoByConDt(ptUpMapIn);
	                    if (0 == pr) {
	                        // 新增题型，需要插入
	                        PatientContentData pcdVo = new PatientContentData();
	                        pcdVo.setContentId("");
	                        pcdVo.setCreateTime(updateTime);
	                        pcdVo.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
	                        pcdVo.setQuestionAnswer(quesvalue);
	                        pcdVo.setQuestionId(queskey);
	                        pcdVo.setTaskId(taskId);
	                        pcdVo.setUpdateAccept(updateAccept);
	                        pcdVo.setUpdateTime(updateTime);
	                        pcdVo.setUpdateType(Constants.UPDATE_TYPE_INSERT);
	                        pcdVo.setUserId(userId);
	                        pcdVo.setPtSchemeid(ptSchemeId);
	                        pcdVo.setTemplType("0");
	                        pcdVo.setQueueId(queueId);
	                        pcdVo.setTenantId(tenantId);
	                        pcdVo.setSourceTypeCreate(sourceType);
	                        pcdVo.setSourceTypeUpdate(sourceType);
	                        ptcInList.add(pcdVo);
	                    }
	                }
	                if (!CollectionUtils.isEmpty(ptcInList)) {
	                    patientTaskConDao.savePatientTaskContentDataBatch(ptcInList);
	                }
	                // 更新历史轨迹
	                HashMap<String, Object> hisConDataMap = new HashMap<String, Object>();
	                hisConDataMap.put("taskId", taskId);
	                hisConDataMap.put("updateAccept", updateAccept);
	                hisConDataMap.put("updateTime", updateTime);
	                hisConDataMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
	                hisConDataMap.put("contTemplType", "0");
	                patientTaskConDao.insertContentDataHis(hisConDataMap);
	            }
	        }

		return paramMap;
	}
	
}
